package com.qinggeng.framework.config.mq.impl;

import com.alibaba.fastjson.JSON;
import com.qinggeng.common.enums.OrdersStatusEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.framework.config.mq.dto.MessageOrdersDTO;
import com.qinggeng.framework.config.mq.handle.MessageHandle;
import com.qinggeng.project.system.domain.Orders;
import com.qinggeng.project.system.service.IOrdersService;
import com.qinggeng.project.system.service.IUserAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
public class OrdersEndStatusHandleImpl implements MessageHandle {

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IUserAccountService userAccountService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handle(String msg) {

        log.info("订单完结状态处理{}"+msg);

        MessageOrdersDTO ordersDTO= JSON.parseObject(msg,MessageOrdersDTO.class);

        Orders orders=ordersService.selectOrdersByOrdersNo(ordersDTO.getOrdersNo());
        if(null==orders){
            throw new CustomException("订单不存在");
        }
        try{
            //更新订单状态为完结状态
            if(!ordersService.updateOrdersEndStatus(orders.getOrdersId())){
                log.error("更新完结状态失败");
                throw new CustomException("更新完结状态失败");
            }
            //订单返现
            if(!userAccountService.orderPayMoney(orders.getOrdersNo())){
                log.error("返现失败");
                throw new CustomException("返现失败");
            }
        }catch (Exception e){
            log.error(e.getMessage());
            throw new CustomException(e.getMessage());
        }
    }
}
